<template>
  <div class="row">
    <div class="col-xs-12 col-sm-6 col-md-4 q-pa-md">
      <!-- :rows="data" :visible-columns="visibleColumns" -->
      <!-- <q-card>{{ data.length }}</q-card> -->
      <q-table
        class="my-sticky-header-last-column-table"
        :rows="data"
        :columns="columns"
        :loading="loading"
        no-data-label="暂无数据"
        row-key="id"
        :filter="filter"
        flat
        bordered
        v-model:pagination="pagination"
        hide-pagination
      >
        <!-- 对于表格列的插槽 -->
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="id" :props="props">{{ props.row.id }}</q-td>
            <q-td key="name" :props="props">
              <span>{{ props.row.name }}</span>
            </q-td>
            <q-td key="caption" :props="props">
              <span>{{ props.row.caption }}</span>
            </q-td>
            <q-td key="dataClickAction" :props="props">
              <q-btn
                unelevated
                @click="onEditClickAction(props.row.id)"
                color="primary"
                label="详情"
                flat
                dense
              ></q-btn>
              <q-btn
                unelevated
                @click="onPageChangeAction(props.row.id)"
                color="primary"
                label="页面切换"
                flat
                dense
              ></q-btn>
            </q-td>
          </q-tr>
        </template>
        <!-- <template v-slot:loading>
          <q-inner-loading showing color="primary" />
        </template> -->
        <!-- 对于上面的插槽 -->
        <template v-slot:top>
          <q-btn
            color="primary"
            :disable="loading"
            label="开始"
            @click="addRow"
          />
          <q-btn
            v-if="data.length !== 0"
            class="q-ml-sm"
            color="primary"
            :disable="loading"
            label="停止"
            @click="removeRow"
          />
          <q-space />
          <q-input
            borderless
            dense
            debounce="300"
            v-model="filter"
            placeholder="Search"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
        </template>
      </q-table>

      <div class="row justify-center q-mt-md">
        <q-pagination
          v-model="pagination.page"
          color="grey-8"
          :max="pagesNumber"
          size="sm"
        />
      </div>

      <q-dialog v-model="confirm" persistent>
        <q-card>
          <q-card-section class="row items-center">
            <q-avatar
              icon="signal_wifi_off"
              color="primary"
              text-color="white"
            />
            <span class="q-ml-sm">这是数据详情信息</span>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat label="Cancel" color="primary" v-close-popup />
            <q-btn flat label="Turn on Wifi" color="primary" v-close-popup />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </div>
</template>

<style></style>

<script>
import { useQuasar } from "quasar";
import {
  ref,
  computed,
  onMounted,
  onActivated,
  onUpdated,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { metadataTableService } from "../service/metadataTableService";

const columns = [
  {
    name: "id",
    label: "编号",
    align: "left",
    field: (row) => row.id,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "name",
    required: true,
    label: "名称",
    align: "left",
    field: (row) => row.name,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "caption",
    required: true,
    label: "中文名称",
    align: "left",
    field: (row) => row.caption,
    format: (val) => `${val}`,
    sortable: true,
  },
  // {
  //   name: "pluralName",
  //   required: true,
  //   label: "复数",
  //   align: "left",
  //   field: (row) => row.pluralName,
  //   format: (val) => `${val}`,
  //   sortable: true,
  // },
  // {
  //   name: "tableName",
  //   required: true,
  //   label: "表名称",
  //   align: "left",
  //   field: (row) => row.tableName,
  //   format: (val) => `${val}`,
  //   sortable: true,
  // },
  // {
  //   name: "engine",
  //   required: true,
  //   label: "引擎",
  //   align: "left",
  //   field: (row) => row.engine,
  //   format: (val) => `${val}`,
  //   sortable: true,
  // },
  // {
  //   name: "createdDate",
  //   required: true,
  //   label: "创建时间",
  //   align: "left",
  //   field: (row) => row.createdDate,
  //   format: (val) => `${val}`,
  //   sortable: true,
  // },
  // {
  //   name: "lastModifiedDate",
  //   required: true,
  //   label: "修改时间",
  //   align: "left",
  //   field: (row) => row.lastModifiedDate,
  //   format: (val) => `${val}`,
  //   sortable: true,
  // },
  {
    name: "dataClickAction",
    align: "center",
    label: "操作",
    field: "dataClickAction",
    sortable: true,
  },
];

const visibleColumns = [
  "id",
  "name",
  "caption",
  // "pluralName",
  // "tableName",
  // "engine",
  // "createdDate",
  // "lastModifiedDate",
  "dataClickAction",
];

export default {
  name: "PageSignal",

  setup() {
    const $router = useRouter();
    const data = ref([]);
    const confirm = ref(false);
    const $q = useQuasar();
    const pagination = ref({
      sortBy: "desc",
      descending: false,
      page: 1,
      rowsPerPage: 5,
      rowsNumber: 0,
    });
    const loading = ref(false);
    const filter = ref("");

    const rowCount = ref(0);
    let timer = 0;
    let count = 0;
    function onEditClickAction(id) {
      confirm.value = true;
    }
    function onPageChangeAction(id) {
      $router.push({ path: "/setting/", query: { id } });
    }
    function init(params) {
      console.info("init");
      // this.$store.commit(
      //   "config/updateIsAllowBack",
      //   this.$route.meta.isAllowBack
      // );

      // this.selected = [];
      // this.search = "";
      // this.dataSource = dataSource || this.$route.params.dataSource;
      // this.dataSourceUrl = "/dataSource/" + this.dataSource;
    }
    function onRefresh() {
      fetchFromServer();
    }
    function fetchFromServer() {
      console.info("onRefresh");
      loading.value = true;
      data.value = [];
      $q.loading.show({
        message: "加载中",
      });

      try {
        let query = getQuery();

        // this.pagination.count = await metadataTableService.count(
        //   this.dataSource,
        //   this.search,
        //   query
        // );

        // let data = await metadataTableService.list(
        //   this.dataSource,
        //   this.pagination.page,
        //   this.pagination.rowsPerPage,
        //   this.search,
        //   query
        // );
        let temp = JSON.parse(
          '[{"autoIncrement":true,"caption":"编号","createdDate":1706460574038,"dataType":"BIGINT","description":"主键","displayOrder":0,"displayable":false,"id":10483,"indexName":"primary_key_30","indexType":"PRIMARY","insertable":false,"lastModifiedDate":1706460574038,"length":20,"multipleValue":false,"name":"id","nullable":false,"queryable":false,"systemable":false,"unsigned":true,"updatable":false},{"autoIncrement":false,"caption":"名称","createdDate":1706460574038,"dataType":"VARCHAR","description":"名称","displayOrder":1,"displayable":true,"id":10484,"insertable":true,"lastModifiedDate":1706460574038,"length":200,"multipleValue":false,"name":"name","nullable":false,"queryable":true,"systemable":false,"unsigned":false,"updatable":true},{"autoIncrement":false,"caption":"全文索引","createdDate":1706460574038,"dataType":"TEXT","description":"全文索引","displayOrder":2,"displayable":false,"id":10485,"indexName":"ft_fulltext_body_30","indexType":"FULLTEXT","insertable":false,"lastModifiedDate":1706460574038,"multipleValue":false,"name":"fullTextBody","nullable":true,"queryable":false,"systemable":false,"unsigned":false,"updatable":false},{"autoIncrement":false,"caption":"创建时间","createdDate":1706460574038,"dataType":"DATETIME","description":"创建时间","displayOrder":3,"displayable":false,"id":10486,"insertable":false,"lastModifiedDate":1706460574038,"multipleValue":false,"name":"createdDate","nullable":false,"queryable":false,"systemable":false,"unsigned":false,"updatable":false},{"autoIncrement":false,"caption":"修改时间","createdDate":1706460574038,"dataType":"DATETIME","description":"修改时间","displayOrder":4,"displayable":false,"id":10487,"insertable":false,"lastModifiedDate":1706460574038,"multipleValue":false,"name":"lastModifiedDate","nullable":true,"queryable":false,"systemable":false,"unsigned":false,"updatable":false}]'
        );

        data.value = temp;
        console.log("temp" + data.value[0].caption);
        rowCount.value = temp.length;
        loading.value = false;
        $q.loading.hide();
      } catch (error) {
        loading.value = false;
        $q.loading.hide();
      }
    }
    function getQuery() {
      let query = {};
      // for (let i = 0; i < this.queryColumns.length; i++) {
      //   const queryColumn = this.queryColumns[i];
      //   if (queryColumn.value && queryColumn.value.trim() !== "") {
      //     query[queryColumn.name] = queryColumn.value
      //   }
      // }
      return query;
    }

    //组件挂载完成后执行的函数(只执行一次)
    onMounted(() => {
      console.log("页面挂载完成，触发了onMounted钩子函数");
      // timer = setInterval(() => {
      //   console.log("定时器正在运行中", count++);
      // }, 1000);
      init();
      onRefresh();
    });
    //组件被激活时执行的函数(每次进去都执行)
    onActivated(() => {
      // console.log("刷新");
    });
    onUpdated(() => {
      console.log("数据发生了更新，触发了onUpdated钩子函数");
    });
    onUnmounted(() => {
      console.log("页面/组件退出，触发了onUnmounted钩子函数");
      // 如果不清楚，这些异步的行为就会常驻在内存中，一定程度上会造成常驻内存的不必要消耗，造成内存泄露
      // clearInterval(timer);
    });
    return {
      data,
      pagination,
      columns,
      loading,
      filter,
      rowCount,
      visibleColumns,
      confirm,
      onEditClickAction,
      onPageChangeAction,
      pagesNumber: computed(() =>
        Math.ceil(data.value.length / pagination.value.rowsPerPage)
      ),
      dateFormat: function (value) {
        return date.dateTimeFormat(value);
      },

      // emulate fetching data from server
      addRow() {
        loading.value = true;
        setTimeout(() => {
          const index = Math.floor(Math.random() * (data.value.length + 1)),
            row = originalRows[Math.floor(Math.random() * originalRows.length)];
          if (data.value.length === 0) {
            rowCount.value = 0;
          }
          row.id = ++rowCount.value;
          const newRow = { ...row }; // extend({}, row, { name: `${row.name} (${row.__count})` })
          data.value = [
            ...data.value.slice(0, index),
            newRow,
            ...data.value.slice(index),
          ];
          loading.value = false;
        }, 500);
      },

      removeRow() {
        loading.value = true;
        setTimeout(() => {
          const index = Math.floor(Math.random() * data.value.length);
          data.value = [
            ...data.value.slice(0, index),
            ...data.value.slice(index + 1),
          ];
          loading.value = false;
        }, 500);
      },
    };
  },
};
</script>
<style lang="sass">
.my-sticky-header-last-column-table
  /* height 和 max-height 很重要 */
  height: 410px

  /* 为了在任何浏览器窗口上都正确的突出显示固定的列，我们需要声明 max-width 属性 */
  max-width: 600px

  td:last-child
    /* 最后一列的背景颜色 */
    background-color: #e5eff3

  /** 固定表头 */
  tr th
    position: sticky
    /* 表头（tr th）的 z-index 要比下面的 td 高 */
    z-index: 2
    /* 表头的背景颜色 */
    color: #fff
    background: #35c8e8

  /* 这将是加载指示器 */
  thead tr:last-child th
    /* 所有前面表头行的高度 */
    top: 48px
    /* 最高的 z-index */
    z-index: 3
  thead tr:first-child th
    top: 0
    z-index: 1
  tr:last-child th:last-child
    /* 最高的 z-index */
    z-index: 3

  td:last-child
    z-index: 1

  /** 固定最后一列 */
  td:last-child, th:last-child
    position: sticky
    right: 0

  /* 在焦点聚焦在固定顶部行时防止滚动 */
  tbody
    /* 所有前面表头行的高度 */
    scroll-margin-top: 48px
</style>
